<?php
namespace app\model;
use think\Db;
use think\Model;
use tsms\Tsms;

class Sms extends Model{

  public function send($mobile){
    $result = [];
    $result['ret'] = 0;
    $appid = '1400089444';
    $appkey = 'a7c2b529c0a02cc5fc23e108bb0f0327';
    $templateid = 118025;
    $code = rand(111111,999999);
    $params = [$code];
    $sign = '夏日已逝';
    $sms = new Tsms($appid,$appkey);
    //发送
    $res_sms = $sms->sendWithParam('86',$mobile,$templateid,$params,$sign,'','');
    $res_sms = json_decode($res_sms,true);
    if($res_sms['result'] == 0){
      $result['ret'] = 1;
      $result['msg'] = '发送成功';
      //插入sms记录表
      $base['mobile'] = $mobile;
      $base['code'] = $code;
      $base['ctime'] = time();
      $res_create = self::create($base);
    }else{
      $result['msg'] = $res_sms['errmsg'];
    }
    return $result;
  }

  public function check($mobile,$code){
    $result = [];
    $result['ret'] = 0;
    $wh['mobile'] = $mobile;
    $up['code'] = $code;
    $sql = "select * from `#__sms` where `mobile`=? order by `ctime` desc";
    $res = Db::query($sql,[$mobile]);
    if($res && count($res)>0){
      if((time() - $res[0]['ctime'])<300){
        if($res[0]['code'] == $code){
          $result['ret'] = 1;
          $result['msg'] = '验证通过';
        }else{
          $result['msg'] = '验证码不正确';
        }
      }else{
        $result['msg'] = '验证码过期，请重新获取';
      }
    }else{
      $result['msg'] = '验证码不正确';
    }
    return $result;
  }



}//END